using System;
using System.Collections.Generic;
using Sce.Pss.Core.Graphics;

namespace ResourceManager
{
	public class Library : IDisposable
	{
		#region Variables
		private GraphicsContext _graphics;
		private Dictionary<string,ResourcesStruct.SpriteResource> _loadedSprites;
		#endregion
		
		private static Library _instance;
		public static Library Instance
		{
			get{
				if(_instance == null)
				{
					_instance = new Library();
				}
				return _instance;
			}
		}
		
		private Library ()
		{
		}

		public void Init (GraphicsContext graphics)
		{
			_graphics = graphics;
			_loadedSprites = new Dictionary<string, ResourcesStruct.SpriteResource>();
		}
		
		public Sprite GetSprite(string path)
		{
			if(_loadedSprites.ContainsKey(path))
			{
				var res = _loadedSprites[path];
				res.LinksCount += 1;
				return _loadedSprites[path].Sprite;
			}
			
			// if we don't have sprite
			Texture2D myTexture;
			myTexture = new Texture2D(path, false);
        	myTexture.SetWrap(TextureWrapMode.ClampToEdge);
			Sprite sprite = new Sprite(myTexture, 10.0f, 20.0f);
			
			RegisterSprite(sprite, path);
			return sprite;
		}
		
		public void ReleaseSprite(string path)
		{
			if(!_loadedSprites.ContainsKey(path))
			{
				Console.WriteLine("WARNING: Resource '{0}' already released", path);
				return;
			}
			
			var res = _loadedSprites[path];
				res.LinksCount -= 1;
			if(_loadedSprites[path].LinksCount ==0)
			{
				_loadedSprites[path].Sprite.Dispose();
				_loadedSprites.Remove(path);
			}
		}

		private void RegisterSprite (Sprite sprite, string path)
		{
			ResourcesStruct.SpriteResource resource = new ResourcesStruct.SpriteResource();
			resource.Sprite = sprite;
			resource.LinksCount = 1;
			_loadedSprites.Add(path,resource);
		}
		
		public void Dispose()
		{
			if(_loadedSprites != null)
			{
				foreach(ResourcesStruct.SpriteResource item in _loadedSprites.Values)
				{
					if(item.Sprite != null)
						item.Sprite.Dispose();
				}
			}
		}
	}
}

